
#include <string>
#include <iostream>
#include <cerrno>
#include <cstring>
#include <cstdlib>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <netdb.h>

int rsockfd;

void* readf()
{
	char buffer[255];
//	std::cout << "I will read in 20 seconds. My socket is ` " << sockfd << std::endl;
	std::cout << "Starting to read !" << std::endl;
      while(true){
		memset(buffer, 0, sizeof(buffer));
		int n = ::read(rsockfd, buffer, 255);
		if(n < 0) {
			std::cerr << "ERROR reading from socket" << std::endl;
		}
		std::cout << buffer << rsockfd << std::endl;
	}
}


void* run_server(void*)
{
	int portno = 6565;
	int new_sockfd ;
	//creates new socket IPv4 TCP and stores descriptor in sockfd
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0) {
		std::cerr << "ERROR opening socket" << std::endl;
	}
	//Creates and initializes sock_addr_in structure.
	sockaddr_in serv_addr;
	memset(&serv_addr, 0, sizeof(sockaddr_in));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = INADDR_ANY;
	// htons converts 16bit integer to network byte order.
	serv_addr.sin_port = htons(portno);
	if(bind(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
		std::cerr << "Can't bind socket: errno " << errno << std::endl;
	}
	// Start listening for incoming connections, 5 is size of backlog queue.
	listen(sockfd, 10);
	sockaddr_in cli_addr;
	socklen_t cli_len = sizeof(cli_addr);
	std::cout << "server run successfully " << std::endl;
	while(new_sockfd = accept(sockfd, (sockaddr*)&cli_addr, &cli_len)){
		char* host_name = inet_ntoa(cli_addr.sin_addr);
		std::cout << "Conenction from " << host_name << std::endl; 
		rsockfd = new_sockfd;
		readf();
	}
}
int main()
{
	pthread_t p_read;
	pthread_t p_run;
	pthread_create(&p_run, NULL, run_server, NULL);
	char buffer[255];
	while(true){
		std::cout <<"serv sock"<< rsockfd << std::endl;
		memset(buffer,0,255);
		std::cout << "insert text to send" << std::endl;
		std::cin >> buffer;
		write(rsockfd, buffer, 255);}

	sleep(1000);
	return 0;
}
